package com.riche.codefactory.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.riche.codefactory.annotation.AuthCheck;
import com.riche.codefactory.common.BaseResponse;
import com.riche.codefactory.common.DeleteRequest;
import com.riche.codefactory.common.ErrorCode;
import com.riche.codefactory.common.R;
import com.riche.codefactory.constant.UserConstant;
import com.riche.codefactory.exception.BusinessException;
import com.riche.codefactory.exception.ThrowUtils;
import com.riche.codefactory.model.c2s.question.C2sQuestionQueryRequest;
import com.riche.codefactory.model.c2s.questionBank.C2sQuestionBankAddRequest;
import com.riche.codefactory.model.c2s.questionBank.C2sQuestionBankEditRequest;
import com.riche.codefactory.model.c2s.questionBank.C2sQuestionBankQueryRequest;
import com.riche.codefactory.model.c2s.questionBank.C2sQuestionBankUpdateRequest;
import com.riche.codefactory.model.domain.Question;
import com.riche.codefactory.model.domain.QuestionBank;
import com.riche.codefactory.model.domain.User;
import com.riche.codefactory.model.s2c.S2cQuestionBank;
import com.riche.codefactory.service.IQuestionBankSVC;
import com.riche.codefactory.service.IQuestionSVC;
import com.riche.codefactory.service.IUserSVC;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 题库接口
 *
 */
@RestController
@RequestMapping("/questionBank")
@Slf4j
public class QuestionBankController {

    @Resource
    private IQuestionBankSVC IQuestionBankSVC;

    @Resource
    private IUserSVC userService;

    @Resource
    private IQuestionSVC IQuestionSVC;

    // region 增删改查

    /**
     * 创建题库
     *
     * @param c2sQuestionBankAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addQuestionBank(@RequestBody C2sQuestionBankAddRequest c2sQuestionBankAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(c2sQuestionBankAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        QuestionBank questionBank = new QuestionBank();
        BeanUtils.copyProperties(c2sQuestionBankAddRequest, questionBank);
        // 数据校验
        IQuestionBankSVC.validQuestionBank(questionBank, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        questionBank.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = IQuestionBankSVC.save(questionBank);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newQuestionBankId = questionBank.getId();
        return R.ok(newQuestionBankId);
    }

    /**
     * 删除题库
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestionBank(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        QuestionBank oldQuestionBank = IQuestionBankSVC.getById(id);
        ThrowUtils.throwIf(oldQuestionBank == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestionBank.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = IQuestionBankSVC.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return R.ok(true);
    }

    /**
     * 更新题库（仅管理员可用）
     *
     * @param c2sQuestionBankUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestionBank(@RequestBody C2sQuestionBankUpdateRequest c2sQuestionBankUpdateRequest) {
        if (c2sQuestionBankUpdateRequest == null || c2sQuestionBankUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        QuestionBank questionBank = new QuestionBank();
        BeanUtils.copyProperties(c2sQuestionBankUpdateRequest, questionBank);
        // 数据校验
        IQuestionBankSVC.validQuestionBank(questionBank, false);
        // 判断是否存在
        long id = c2sQuestionBankUpdateRequest.getId();
        QuestionBank oldQuestionBank = IQuestionBankSVC.getById(id);
        ThrowUtils.throwIf(oldQuestionBank == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = IQuestionBankSVC.updateById(questionBank);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return R.ok(true);
    }

    /**
     * 根据 id 获取题库（封装类）
     *
     * @param c2sQuestionBankQueryRequest
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<S2cQuestionBank> getQuestionBankVOById(C2sQuestionBankQueryRequest c2sQuestionBankQueryRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(c2sQuestionBankQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long id = c2sQuestionBankQueryRequest.getId();
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        QuestionBank questionBank = IQuestionBankSVC.getById(id);
        ThrowUtils.throwIf(questionBank == null, ErrorCode.NOT_FOUND_ERROR);
        // 查询题库封装类
        S2cQuestionBank s2cQuestionBank = IQuestionBankSVC.getQuestionBankVO(questionBank, request);
        // 是否要关联查寻题库下的列表
        boolean needQueryQuestionList = c2sQuestionBankQueryRequest.isNeedQueryQuestionList();
        if (needQueryQuestionList) {
            C2sQuestionQueryRequest c2sQuestionQueryRequest = new C2sQuestionQueryRequest();
            int pageSize = c2sQuestionBankQueryRequest.getPageSize();
            c2sQuestionQueryRequest.setPageSize(pageSize);
            c2sQuestionQueryRequest.setQuestionBankId(id);
            c2sQuestionQueryRequest.setCurrent(c2sQuestionBankQueryRequest.getCurrent());
            Page<Question> questionPage = IQuestionSVC.listQuestionByPage(c2sQuestionQueryRequest);
            s2cQuestionBank.setQuestionPage(IQuestionSVC.getQuestionVOPage(questionPage, request));
        }
        // 获取封装类
        return R.ok(s2cQuestionBank);
    }

    /**
     * 分页获取题库列表（仅管理员可用）
     *
     * @param c2sQuestionBankQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<QuestionBank>> listQuestionBankByPage(@RequestBody C2sQuestionBankQueryRequest c2sQuestionBankQueryRequest) {
        long current = c2sQuestionBankQueryRequest.getCurrent();
        long size = c2sQuestionBankQueryRequest.getPageSize();
        // 查询数据库
        Page<QuestionBank> questionBankPage = IQuestionBankSVC.page(new Page<>(current, size),
                IQuestionBankSVC.getQueryWrapper(c2sQuestionBankQueryRequest));
        return R.ok(questionBankPage);
    }

    /**
     * 分页获取题库列表（封装类）
     *
     * @param c2sQuestionBankQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<S2cQuestionBank>> listQuestionBankVOByPage(@RequestBody C2sQuestionBankQueryRequest c2sQuestionBankQueryRequest,
                                                                        HttpServletRequest request) {
        long current = c2sQuestionBankQueryRequest.getCurrent();
        long size = c2sQuestionBankQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 200, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionBank> questionBankPage = IQuestionBankSVC.page(new Page<>(current, size),
                IQuestionBankSVC.getQueryWrapper(c2sQuestionBankQueryRequest));
        // 获取封装类
        return R.ok(IQuestionBankSVC.getQuestionBankVOPage(questionBankPage, request));
    }

    /**
     * 分页获取当前登录用户创建的题库列表
     *
     * @param c2sQuestionBankQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<S2cQuestionBank>> listMyQuestionBankVOByPage(@RequestBody C2sQuestionBankQueryRequest c2sQuestionBankQueryRequest,
                                                                          HttpServletRequest request) {
        ThrowUtils.throwIf(c2sQuestionBankQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        c2sQuestionBankQueryRequest.setUserId(loginUser.getId());
        long current = c2sQuestionBankQueryRequest.getCurrent();
        long size = c2sQuestionBankQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionBank> questionBankPage = IQuestionBankSVC.page(new Page<>(current, size),
                IQuestionBankSVC.getQueryWrapper(c2sQuestionBankQueryRequest));
        // 获取封装类
        return R.ok(IQuestionBankSVC.getQuestionBankVOPage(questionBankPage, request));
    }

    /**
     * 编辑题库（给用户使用）
     *
     * @param c2sQuestionBankEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> editQuestionBank(@RequestBody C2sQuestionBankEditRequest c2sQuestionBankEditRequest, HttpServletRequest request) {
        if (c2sQuestionBankEditRequest == null || c2sQuestionBankEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        QuestionBank questionBank = new QuestionBank();
        BeanUtils.copyProperties(c2sQuestionBankEditRequest, questionBank);
        // 数据校验
        IQuestionBankSVC.validQuestionBank(questionBank, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = c2sQuestionBankEditRequest.getId();
        QuestionBank oldQuestionBank = IQuestionBankSVC.getById(id);
        ThrowUtils.throwIf(oldQuestionBank == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestionBank.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = IQuestionBankSVC.updateById(questionBank);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return R.ok(true);
    }

    // endregion
}
